package com.hudilao.service.impl;

import com.alibaba.druid.util.HttpClientUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hudilao.common.constant.MessageConstant;
import com.hudilao.dto.CustomerLoginDTO;
import com.hudilao.entity.Customer;
import com.hudilao.exception.LoginFailedException;
import com.hudilao.mapper.CustomerMapper;
import com.hudilao.properties.WeChatProperties;
import com.hudilao.service.CustomerService;
import com.hudilao.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper,Customer> implements CustomerService {

    //微信接口地址
    private static final String WX_LOGIN_ADDRESS = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private CustomerMapper customerMapper;


    /**
     * 微信用户登录
     * @param customerLoginDTO
     * @return
     */
    @Override
    public Customer wechatLogin(CustomerLoginDTO customerLoginDTO) {

        String openid = getOpenid(customerLoginDTO.getCode());

        //判断openid是否为空，空则登录失败，抛出异常
        if(openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //是否为该湖底捞餐厅的新用户
        Customer customer = customerMapper.getByOpenid(openid);     //根据openid查询用户

        //是新用户，完成注册   后面改成弹出会员登陆注册界面
        if(customer == null){
            customer = customer.builder()
                    .openid(openid)
                    .build();
            customerMapper.insert(customer);
        }

        //返回该用户对象

        return customer;
    }

    /**
     * 调用微信接口服务，获得当前微信用户openid
     * @param code
     * @return
     */
    private String getOpenid(String code){
        Map<String, String> map = new HashMap<>();              //map存放微信登录的请求参数
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type","authorization_code");

        String json = HttpClientUtil.doGet(WX_LOGIN_ADDRESS,map);             //调用微信接口服务,返回json数据包

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        return openid;
    }
}
